// 花越开越多，T天如果可行（能制作），T+1,T+2,...天都可行（能制作）- 单调分段
// 判定：mid天的开花情况，能否制作m束花，每束花是连续的k朵

// 判定：第T天的开花情况，能否制作m束花，每束花是连续的k朵
var validateOnDay = function(bloomDay, m, k, now) {
    let bouquet = 0;
    let consecutive = 0;
    for (let bloom of bloomDay) {
        if (bloom <= now) {
            consecutive++;
            if (consecutive == k) {
                bouquet++;
                consecutive = 0;
            }
        } else {
            consecutive = 0;
        }
    }
    return bouquet >= m;
};


/**
 * @param {number[]} bloomDay
 * @param {number} m
 * @param {number} k
 * @return {number}
 */
var minDays = function(bloomDay, m, k) {
    let latestBloom = 0;
    for (let bloom of bloomDay) {
        latestBloom = Math.max(latestBloom, bloom);
    }
    let left = 0, right = latestBloom + 1;
    while (left < right) {
        let mid = (left + right) >> 1;
        if (validateOnDay(bloomDay, m, k, mid)) {
            right = mid;
        } else {
            left = mid + 1;
        }
    }
    if (right == latestBloom + 1) return -1;
    return right;
};